import time

from flask import Flask
from flask import  request
from selenium.webdriver.common.by import  By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
import  flask
import  pyautogui
from  selenium import  webdriver
class GenerationRequest():
    src: str
    prompt: str


    steps: int = 50


    height: int = 512
    width: int = 512

    scale: float = 7.0

    seed: int = None

    strength: float = 0.69
    noise: float = 0.667
    id: str


def getP(r: GenerationRequest):
    driver = webdriver.Chrome()

    # 获取prompt
    prompt = "{}     args:id={}&step={}&strength={}&noise={}&width={}&height={}".format(r['prompt'],r['id'],r['steps'],r['strength'],r['noise'],r['width'],r['height'])

    # 进入ui界面
    driver.get("http://localhost:6969")
    wait = WebDriverWait(driver, 120)
    # 点击上传图片按钮
    wait.until(expected_conditions.element_to_be_clickable(
        (By.CSS_SELECTOR,
         "#__next > div.sc-fmixVB.gIlrWD > div.sc-iuxOeI.dGwjEc > div > div.sc-bQmOxr.sc-eAeVAz.kfwzNC.hOuTWu > div.sc-cqQeAO.iOZPnt > div > span:nth-child(1) > button:nth-child(2)")))
    driver.find_element(By.CSS_SELECTOR,
                        "#__next > div.sc-fmixVB.gIlrWD > div.sc-iuxOeI.dGwjEc > div > div.sc-bQmOxr.sc-eAeVAz.kfwzNC.hOuTWu > div.sc-cqQeAO.iOZPnt > div > span:nth-child(1) > button:nth-child(2)").click()

    # 使用pyautogui来选择图片
    time.sleep(2)
    pyautogui.moveTo(707, 859)
    pyautogui.click()
    pyautogui.write(r['src'])
    print(r['src'])
    time.sleep(2)
    pyautogui.press("enter")
    pyautogui.press("enter")
    # 上传图片后点击生成按钮
    driver.find_element(By.CSS_SELECTOR, "#prompt-input-0").send_keys(prompt)
    time.sleep(2)
    driver.find_element(By.CSS_SELECTOR,
                        "#__next > div.sc-fmixVB.gIlrWD > div.sc-iuxOeI.dGwjEc > div > div.sc-bQmOxr.sc-eAeVAz.kfwzNC.hOuTWu > div.sc-gInZnl.gzmmuf > div.sc-eJKXev.kFMQLm > div.sc-hTRxPq.jBtxjT").click()

    driver.quit()



# 创建 Flask 应用
app = Flask(__name__)


# 创建路由
@app.post('/do')
def do():
    r = request.json
    getP(r)
    return ""

# 运行应用
if __name__ == '__main__':
    app.run()